package cn.com.wxUtil;

import java.math.BigDecimal;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;

import cn.com.Enum.OrderStatus;
import cn.com.constant.Code;
import cn.com.db.model.DiyOrder;
import cn.com.db.model.Order;
import cn.com.db.model.WxPayResult;
import cn.com.db.service.DiyOrderService;
import cn.com.db.service.OrderService;
import cn.com.db.service.WxPayResultService;
import cn.com.util.DataResult;
import cn.com.util.JsonUtil;
import cn.com.util.TimeUtil;
import cn.com.util.UidUtil;

/**
 * 返回给前端调用支付5个参数json字符串封装 
 * @Param priceString:价格,整数,单位分,字符串
 * @Param orderIdList:订单集合(用|分割) 
 * @Param code:前端生成登陆code 
 * @Param body:商品描述 
 * @Param backUrl:回调url
 * @author mxq
 */
public class ReturnSignUtil {

	public static String getPrepayId(HttpServletRequest request, String orderIdList, String code,
			String backUrl, String body, String priceString, String xprId) throws Exception {
		if (StringUtils.isEmpty(orderIdList)) {
			throw new Exception("订单id不能为空");
		}
		String openid = "";
		String session_key = ""; // 会话密钥session_key 是对用户数据进行加密签名的密钥(暂时没用)
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		String httpUrl = url + "?appid=" + wxConstant.APPID + "&secret=" + wxConstant.SECRET + "&js_code=" + code
				+ "&grant_type=authorization_code";
		String ret = cn.com.util.HttpUtil.doGet(new URL(httpUrl)); // 这里工具类名称重复了
		JSONObject obj = JSONObject.parseObject(ret);
		if (obj.containsKey("errcode")) {
			String errmsg = obj.get("errmsg").toString();
			throw new Exception(errmsg);
		} else if (obj.containsKey("session_key")) {
			// 开始处理userInfo
			openid = obj.get("openid").toString();
			session_key = obj.get("session_key").toString();
		}
		// 登陆结束

		// 时间戳
		String nonce_str = UidUtil.createUUID();
		String ip = request.getRemoteAddr();
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		packageParams.put("appid", wxConstant.APPID);
		packageParams.put("mch_id", wxConstant.MCH_ID);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);// 支付主体
		packageParams.put("out_trade_no", xprId);// 创建微信支付商户订单号
		packageParams.put("total_fee", priceString);// 价格 这里要是字符串
		packageParams.put("spbill_create_ip", ip); // TODO 这里加了客户端ip
		packageParams.put("notify_url", backUrl);// 支付结束微信服务器回调地址
													// 118.24.106.223:8080
		packageParams.put("trade_type", "JSAPI");// 这个api有，固定的
		packageParams.put("openid", openid);// openid

		String mysign = PayCommonUtil.createSign("UTF-8", packageParams, wxConstant.PAY_KEY); // 最后这个是自己设置的32位密钥
		packageParams.put("sign", mysign);
		// 转成XML
		String xml = "<xml>" + "<appid>" + wxConstant.APPID + "</appid>" + "<body><![CDATA[" + body + "]]></body>"
				+ "<mch_id>" + wxConstant.MCH_ID + "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>"
				+ "<notify_url>" + backUrl + "</notify_url>" + "<openid>" + openid + "</openid>" + "<out_trade_no>"
				+ xprId + "</out_trade_no>" + "<spbill_create_ip>" + ip + "</spbill_create_ip>" + "<total_fee>"
				+ priceString + "</total_fee>" + "<trade_type>" + "JSAPI" + "</trade_type>" + "<sign>" + mysign
				+ "</sign>" + "</xml>";
		String result = PayUtil.httpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xml);
		System.out.println(result);
		// 解析XML存入Map
		// Map map = XMLUtil.doXMLParse(resXml);
		Map map = PayUtil.doXMLParse(result);
		// 得到prepay_id
		String prepay_id = (String) map.get("prepay_id");
		return prepay_id;
	}

	public static String getFiveParam(String prepay_id) throws Exception {
		SortedMap<Object, Object> packageP = new TreeMap<Object, Object>();
		if (StringUtils.isNotEmpty(prepay_id)) {
			packageP.put("appId", wxConstant.APPID);// ！！！注意，这里是appId,上面是appid，写这个东西的人。。。
			packageP.put("nonceStr", UidUtil.createUUID());
			packageP.put("package", "prepay_id=" + prepay_id);// 必须把package写成
																// "prepay_id="+prepay_id这种形式
			packageP.put("signType", "MD5");// paySign加密
			packageP.put("timeStamp", (System.currentTimeMillis() / 1000) + "");// 时间戳
			// 得到paySign
			String paySign = PayCommonUtil.createSign("UTF-8", packageP, wxConstant.PAY_KEY);
			packageP.put("paySign", paySign);
		} else {
			throw new Exception("获取微信prepay_id失败");
		}
		// 将packageP数据返回给小程序
		DataResult dataResult = new DataResult();
		dataResult.setData(packageP);
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("获取成功");
		return JsonUtil.toJsonString(dataResult);
	}

}
